package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description: 117. 填充每个节点的下一个右侧节点指针 II
 * User: Li_yizYa
 * Date: 2025/5/26
 * Time: 15:19
 */
public class Solution11 {
    public Node1 connect(Node1 root) {
        if (root == null) {
            return null;
        }
        Queue<Node1> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int len = queue.size();
            while (len > 0) {
                Node1 node = queue.poll();
                if (len == 1) {
                    node.next = null;
                } else {
                    node.next = queue.peek();
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
        }
        return root;
    }
}
